<!-- global-tab/index.vue - 全局标签页 -->
<template>
  <div class="global-tabs" :class="{ 'tabs-dark': isDark }">
    <div class="tabs-container">
      <!-- 🎯 标签列表 -->
      <div class="tabs-list" ref="tabsListRef">
        <div
          v-for="tab in tabsList"
          :key="tab.path"
          class="tab-item"
          :class="{ 'is-active': isActive(tab.path) }"
          @click="handleTabClick(tab)"
          @contextmenu.prevent="handleContextMenu($event, tab)"
        >
          <!-- 图标 -->
          <el-icon v-if="tab.icon" class="tab-icon">
            <component :is="getTabIcon(tab.icon)" />
          </el-icon>
          
          <!-- 标题 -->
          <span class="tab-title">{{ tab.title }}</span>
          
          <!-- 关闭按钮 -->
          <el-icon
            v-if="tab.closable"
            class="tab-close"
            @click.stop="handleClose(tab.path)"
          >
            <Close />
          </el-icon>
        </div>
      </div>
      
      <!-- 🎯 操作按钮区 -->
      <div class="tabs-actions">
        <!-- 刷新按钮 -->
        <el-tooltip content="刷新当前页" placement="bottom">
          <el-button
            text
            :icon="Refresh"
            @click="handleRefresh"
            class="action-btn"
          />
        </el-tooltip>
        
        <!-- 更多操作下拉菜单 -->
        <el-dropdown @command="handleCommand" trigger="click">
          <el-button text :icon="ArrowDown" class="action-btn" />
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="closeOther" :icon="Close">
                关闭其他
              </el-dropdown-item>
              <el-dropdown-item command="closeLeft" :icon="Back">
                关闭左侧
              </el-dropdown-item>
              <el-dropdown-item command="closeRight" :icon="Right">
                关闭右侧
              </el-dropdown-item>
              <el-dropdown-item command="closeAll" :icon="Close" divided>
                关闭所有
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 🎯 右键菜单 -->
    <Teleport to="body">
      <div
        v-show="contextMenuVisible"
        class="tab-context-menu"
        :style="contextMenuStyle"
        @click="closeContextMenu"
      >
        <div class="context-menu-item" @click="handleRefreshTab">
          <el-icon><Refresh /></el-icon>
          <span>刷新</span>
        </div>
        <div
          v-if="contextTab?.closable"
          class="context-menu-item"
          @click="handleClose(contextTab?.path)"
        >
          <el-icon><Close /></el-icon>
          <span>关闭</span>
        </div>
        <el-divider style="margin: 4px 0" />
        <div class="context-menu-item" @click="handleCommand('closeOther')">
          <el-icon><Close /></el-icon>
          <span>关闭其他</span>
        </div>
        <div class="context-menu-item" @click="handleCommand('closeLeft')">
          <el-icon><Back /></el-icon>
          <span>关闭左侧</span>
        </div>
        <div class="context-menu-item" @click="handleCommand('closeRight')">
          <el-icon><Right /></el-icon>
          <span>关闭右侧</span>
        </div>
        <el-divider style="margin: 4px 0" />
        <div class="context-menu-item" @click="handleCommand('closeAll')">
          <el-icon><Close /></el-icon>
          <span>关闭所有</span>
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useTabsStore } from '@/stores/modules/tabs'
import { useTheme } from '@/composables/useTheme.js'
import {
  Close,
  Refresh,
  ArrowDown,
  Back,
  Right,
  Odometer,
  Setting,
  User,
  UserFilled,
  Avatar,
  Document,
  InfoFilled,
  Tools,
  Menu as MenuIcon
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const tabsStore = useTabsStore()
const { isDark } = useTheme()

// 🎯 状态
const tabsListRef = ref(null)
const contextMenuVisible = ref(false)
const contextTab = ref(null)
const contextMenuStyle = ref({})

// 🎯 计算属性
const tabsList = computed(() => tabsStore.tabsList)
const activeTabPath = computed(() => tabsStore.activeTabPath)

// 🎯 初始化
onMounted(() => {
  tabsStore.initTabs()
  // 添加当前路由为标签
  if (route.path !== '/login' && route.path !== '/404') {
    tabsStore.addTab(route)
  }
  
  // 监听全局点击，关闭右键菜单
  document.addEventListener('click', closeContextMenu)
})

onUnmounted(() => {
  document.removeEventListener('click', closeContextMenu)
})

// 🎯 监听路由变化
watch(
  () => route.fullPath,
  () => {
    if (route.path !== '/login' && route.path !== '/404') {
      tabsStore.addTab(route)
    }
  }
)

// 🎯 判断是否激活
function isActive(path) {
  return path === route.path
}

// 🎯 标签点击
function handleTabClick(tab) {
  if (route.path !== tab.path) {
    router.push(tab.path)
  }
}

// 🎯 关闭标签
function handleClose(path) {
  tabsStore.removeTab(path)
  closeContextMenu()
}

// 🎯 刷新当前标签
function handleRefresh() {
  // 使用 router 的 replace 方法强制刷新
  const currentPath = route.path
  router.replace({
    path: '/redirect' + currentPath,
    query: route.query
  })
}

// 🎯 刷新指定标签
function handleRefreshTab() {
  if (contextTab.value) {
    router.replace({
      path: '/redirect' + contextTab.value.path
    })
  }
  closeContextMenu()
}

// 🎯 下拉菜单命令
function handleCommand(command) {
  const currentPath = contextTab.value?.path || route.path
  
  switch (command) {
    case 'closeOther':
      tabsStore.closeOtherTabs(currentPath)
      ElMessage.success('已关闭其他标签')
      break
    case 'closeLeft':
      tabsStore.closeLeftTabs(currentPath)
      ElMessage.success('已关闭左侧标签')
      break
    case 'closeRight':
      tabsStore.closeRightTabs(currentPath)
      ElMessage.success('已关闭右侧标签')
      break
    case 'closeAll':
      tabsStore.closeAllTabs()
      ElMessage.success('已关闭所有标签')
      break
  }
  
  closeContextMenu()
}

// 🎯 右键菜单
function handleContextMenu(event, tab) {
  event.preventDefault()
  
  contextTab.value = tab
  contextMenuVisible.value = true
  
  // 计算菜单位置
  const { clientX, clientY } = event
  contextMenuStyle.value = {
    left: `${clientX}px`,
    top: `${clientY}px`
  }
}

// 🎯 关闭右键菜单
function closeContextMenu() {
  contextMenuVisible.value = false
  contextTab.value = null
}

// 🎯 图标映射
function getTabIcon(iconName) {
  const iconMap = {
    'Odometer': Odometer,
    'Setting': Setting,
    'User': User,
    'UserFilled': UserFilled,
    'Avatar': Avatar,
    'Document': Document,
    'InfoFilled': InfoFilled,
    'Tools': Tools,
    'Menu': MenuIcon
  }
  return iconMap[iconName] || Document
}
</script>

<style lang="scss" scoped>
.global-tabs {
  height: 40px;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  user-select: none;
  
  .tabs-container {
    display: flex;
    height: 100%;
    padding: 0 12px;
    gap: 8px;
  }
  
  // 🎯 标签列表
  .tabs-list {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 4px;
    overflow-x: auto;
    overflow-y: hidden;
    
    // 隐藏滚动条但保持可滚动
    &::-webkit-scrollbar {
      height: 0;
    }
  }
  
  // 🎯 单个标签
  .tab-item {
    display: flex;
    align-items: center;
    gap: 6px;
    height: 28px;
    padding: 0 12px;
    border-radius: 4px;
    background: var(--el-fill-color-lighter);
    border: 1px solid var(--el-border-color-lighter);
    cursor: pointer;
    transition: all 0.3s;
    white-space: nowrap;
    flex-shrink: 0;
    
    &:hover {
      background: var(--el-fill-color-light);
      border-color: var(--el-border-color-light);
      
      .tab-close {
        opacity: 1;
      }
    }
    
    &.is-active {
      background: var(--el-color-primary-light-9);
      border-color: var(--el-color-primary);
      color: var(--el-color-primary);
      
      .tab-icon {
        color: var(--el-color-primary);
      }
      
      .tab-close {
        opacity: 1;
      }
    }
    
    .tab-icon {
      font-size: 14px;
      color: var(--el-text-color-regular);
    }
    
    .tab-title {
      font-size: 13px;
      line-height: 1;
    }
    
    .tab-close {
      font-size: 12px;
      opacity: 0;
      transition: all 0.3s;
      
      &:hover {
        color: var(--el-color-danger);
        transform: scale(1.2);
      }
    }
  }
  
  // 🎯 操作按钮区
  .tabs-actions {
    display: flex;
    align-items: center;
    gap: 4px;
    flex-shrink: 0;
    
    .action-btn {
      padding: 4px;
      font-size: 16px;
      
      &:hover {
        background: var(--el-fill-color-light);
      }
    }
  }
  
  // 🎯 深色模式
  &.tabs-dark {
    .tab-item {
      &.is-active {
        background: rgba(100, 108, 255, 0.2);
      }
    }
  }
}

// 🎯 右键菜单
.tab-context-menu {
  position: fixed;
  z-index: 9999;
  min-width: 140px;
  background: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  box-shadow: var(--el-box-shadow-light);
  padding: 4px;
  
  .context-menu-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 13px;
    color: var(--el-text-color-primary);
    transition: all 0.3s;
    
    &:hover {
      background: var(--el-fill-color-light);
      color: var(--el-color-primary);
    }
    
    .el-icon {
      font-size: 14px;
    }
  }
}
</style>

